import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:zhaoxiaowu_app/global/global.dart';
import 'package:zhaoxiaowu_app/models/login.dart';
import 'package:zhaoxiaowu_app/models/user.dart';
import 'package:zhaoxiaowu_app/utils/event_bus.dart';
import 'package:zhaoxiaowu_app/utils/rsa/rsa_utils.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';

import '../main.dart';

/// 登录状态管理 provider
class LoginViewModel extends ChangeNotifier {
  /// 登录
  /// username: 账号
  /// password: 密码
  void login(String username, String password) async {
    print("login===========");
    print("username = $username");
    print("password = $password");

    if (username.isEmpty) {
      bus.emit("fail", {
        "view": "login",
        "message": "账号不能为空",
      });
      return;
    } else if (password.isEmpty) {
      bus.emit("fail", {
        "view": "login",
        "message": "密码不能为空",
      });
      return;
    }

    _loginRequest(username, password);
  }

  void _loginRequest(String username, String password) async {
    print("登录请求-------------");
    ToastUtils.showActivity("正在登录...");

    SharedPreferences sp = await SharedPreferences.getInstance();

    String pwd = await RSAUtils.encodeString(password);
    Response result = await Global.shared().post(
      "/zxw/user",
      parameters: {"username": username, "password": pwd},
    );

    print(result);

    if (result.data["success"]) {
      ToastUtils.showSuccess("登录成功");

      Login login = Login.fromJson(result.data["data"]);

      Global.shared().token = login.token;
      Global.shared().user = login.user;
      sp.setString("token", login.token);
      Global.shared().setHeaders(login.token);

      Navigator.of(navigatorKey.currentContext!).popAndPushNamed("menu");
    } else {
      bus.emit("fail", {
        "view": "login",
        "message": result.data["msg"],
      });
    }
  }

  void tokenLogin(String token) async {
    SharedPreferences sp = await SharedPreferences.getInstance();

    Response result = await Global.shared().get("/zxw/user");

    print("离线登录" + result.data.toString());

    if (result.data["success"]) {
      User user = User.fromJson(result.data["data"]);

      Global.shared().user = user;
      Navigator.of(navigatorKey.currentContext!).popAndPushNamed("menu");
    } else {
      sp.remove("token");
    }
  }
}
